package org.blackcat.service.impl;

import org.blackcat.common.DESUtil;
import org.blackcat.common.DateUtils;
import org.blackcat.common.StringUtils;
import org.blackcat.common.UUIDUtils;
import org.blackcat.core.annotation.Validation;
import org.blackcat.dao.BloodPressureDao;
import org.blackcat.dao.redis.RedisHandle;
import org.blackcat.domain.BloodPressure;
import org.blackcat.domain.common.MsgResponse;
import org.blackcat.domain.enums.DateEnum;
import org.blackcat.domain.enums.ResponseCodeEnum;
import org.blackcat.domain.enums.UserEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 詹泽
 * @date 2017/2/23
 */
@Service
public class BloodPressureServiceImpl implements org.blackcat.service.BloodPressureService {

    @Autowired
    private BloodPressureDao bloodPressureDao;

    @Autowired
    private RedisHandle redisHandle;

    @Override
    @Validation
    public MsgResponse<Object> addBloodPressure(BloodPressure bloodPressure,String token) throws Exception {
        String idAES = redisHandle.getString(token);
        String userId = DESUtil.aesDecrypt(idAES, UserEnum.USER_AES_KEY.getValue());
        bloodPressure.setId(UUIDUtils.uuid());
        bloodPressure.setUserId(userId);
        bloodPressure.setGmtCreate(new Date());
        bloodPressure.setGmtModified(new Date());
        Integer rs = bloodPressureDao.addBloodPressure(bloodPressure);
        if(rs != null && rs > 0){
            return new MsgResponse<>(ResponseCodeEnum.SUCCESS);
        }
        return new MsgResponse<>(ResponseCodeEnum.EXCEPTION);
    }

    @Override
    public MsgResponse<List<BloodPressure>> listBloodPressure(String token, String date, int status) throws Exception {
        String idAES = redisHandle.getString(token);
        String userId = DESUtil.aesDecrypt(idAES, UserEnum.USER_AES_KEY.getValue());
        if(!(StringUtils.regularMatch(date,"\\d{4}(-\\d{1,2}(-\\d{1,2})?)?"))){
            return new MsgResponse<>(ResponseCodeEnum.REQUEST_PARAMETER_ERROR);
        }
        String minDate = "";
        String maxDate = "";
        if(status == DateEnum.YEAR.getCode()){
            minDate = "2017-01-01 0:0:0";
            maxDate = "2017-12-31 23:59:59";
        }else if(status == DateEnum.MONTH.getCode()){
            String d = date+"-"+"1";
            int maxDay = DateUtils.getMaxDayByMonth(d);
            minDate = date + "-1 0:0:0";
            maxDate = date + "-" + maxDay + " 23:59:59";
        }else if(status == DateEnum.DAY.getCode()){
            minDate = date + " 0:0:0";
            maxDate = date + " 23:59:59";
        }
        List<BloodPressure> list = bloodPressureDao.listBloodPressure(userId,minDate,maxDate);
        return new MsgResponse<>(ResponseCodeEnum.SUCCESS,list);
    }
}
